//index.js
//获取应用实例
const app = getApp()
const Pager = require('components/aotoo/core')
let mkNav = require('components/modules/navlist')

import {data} from './data'

const adapterLikeTab = (data) =>{
  let content = []
  let menus = []
  data.map((item, ii) => {
    item.id = 'ss_'+ item.id
    menus.push({
      title: item.moduleName,
      itemClass: ii === 0 ? 'active' : '',
      id: item.id,
      aim: 'onMenus?id='+item.id+'&idx='+ii
    })
    content.push({
      id: 'c_'+item.id,
      title: {
        title: item.moduleName,
        itemClass: 'title-default mb-default'
      },
      dot: [{
        '@html': {
          content: item.subModule[0].freeContent,
          openTag(name, tag) {
            if (name === 'img') {
              // if (tag['@image'] ['class'] !== 'small-emotion') {
                tag['@image']['lazy-load'] = true
                tag['@image']['bindload'] = 'onloadImg'
              // }
              // else {
              //   tag['@image']['mode'] = 'widthFix'
              // }
            }
            return tag
          }
        },
      }],
      itemClass: ii === 0 ? 'detail-body-item xx': 'detail-body-item'
    })
  })
  return {menus, content}
}

function throttle(fn, interval) {
  var enterTime = 0;//触发的时间
  var gapTime = interval || 100 ;//间隔时间，如果interval不传，则默认300ms
  return function() {
    var context = this;
    var backTime = new Date();//第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(context,arguments);
      enterTime = backTime;//赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  };
}
function debounce(fn,interval){
  var timer;
  var gapTime = interval || 100;//间隔时间，如果interval不传，则默认1000ms
  return function() {
    clearTimeout(timer);
    var context = this;
    var args = arguments;//保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    timer = setTimeout(function() {
      fn.call(context,args);
    }, gapTime);
  };
}

Pager({
  data: {
    pagesClass: '',
    scrollTopPages: 0,
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '详情页', //导航栏 中间的标题
      // url: '/pages/index/index'
    },
    height: app.globalData.navheight,
    header: {
      $$id: 'header'
    },
    body: {
      $$id: 'paegsInst'
    },
    footer: {
      $$id: 'paegsBtn'
    },
    detail: Pager.list({
      // $$id: 'detail'
      data: [],
      listClass: 'ss-detail primary hei-p100',
      type: {
        is: 'scroll',
        'scroll-y': true,
        'scroll-into-view': '',
        // 'scroll-with-animation': true,
        'bindscroll': 'bindscroll',
        enhanced: true,
        'fast-deceleration': true
      },
      header: {
        '@list': {
          $$id: 'menus',
          data: [],
          type: {
            is: 'scroll',
            'scroll-x': true,
            'enable-flex': true,
            enhanced: true,
            'show-scrollbar': false
          },
          itemClass: 'item-title item-menus',
          listClass: 'list-tabs fixed'
        }
      }
    })
  },
  $paegsInst: null,
  execData: [],
  onMenus(e, params, inst) {
    const that = this
    const _idx = params.idx
    const _id = params.id
    this.hasIdx = _idx
    this.scrollUpdateMenus(_id)
    this.clickMenused = true
    this.$menus.css('--show: flex')
    this.$detail.update({'type.scroll-into-view': 'c_'+_id})
  },
  adapter(data, status) {
    const that = this
    const img = (src, type) => {
      let content = []
      let dot = []
      src.map((item, ii) => {
        content.push({
          img: {
            src: item.filePath,
            mode: 'scaleToFill',
            'lazy-load': true
          },
          itemClass: 'item-pic-wrap'
        })
        if (type === 'dot') {
          dot.push({
            title: ' ',
            itemClass: ii === 0 ? 'active' : ''
          })
        }
      })
      return {content, dot}
    }
    const swiperData = img(data.fitments, 'dot')
    const isBanner = {
      data: swiperData.content,
      footer: {
        '@list': {
          $$id: 'swiper-dot-cu',
          data: swiperData.dot,
          listClass: 'ss-banner-dot',
          itemClass: 'item-dot'
        }
      },
      type: {
        is: 'swiper',
        interval: 2000,
        duration: 500,
        bindchange: 'bindchange'
      },
      listClass: 'ss-banner'
    }
    
    that.contentData = adapterLikeTab(data.subStrategy)
    let output = []
    output = [
      {
        '@list': isBanner,
        itemClass: 'ss-relative'
      },
      {
        title: [
          { title: data.productName, itemClass: 'size-title-lg fw-bold color-title' },
          { title: [{title: data.publishDateTime, itemClass: 'color-title'}, {title: data.positionName, itemClass: 'color-default'}], titleClass: 'size-form flex-row-between mtb-default'}
        ],
        titleClass: 'p-default item-head',
      },
      {
        '@list': {
          data: that.contentData.menus,
          itemClass: 'item-title item-menus ',
          listClass: 'list-tabs kkk',
          type: {
            is: 'scroll',
            'scroll-x': true,
            'enable-flex': true
          }
        },
        itemClass: 'menusxx'
      },
      ...that.contentData.content,
      {
        '@list': mkNav({
            data: [{title: '收藏', itemClass: 'nav-item icon-collect', aim: 'onFixedBtn?type=collect'}, {title: '点赞', itemClass: 'nav-item icon-like', aim: 'onFixedBtn?type=like'}, {itemClass: 'nav-item icon-share', '@button': {id: 'case-share', type: 'button', value: '分享', 'open-type': 'share', itemClass: 'ss-btn-text'}}],
          })
      }
    ]
    return output
  },
  onloadImg(e, p, inst) {
    let $width = e.detail.width,    //获取图片真实宽度
        $height = e.detail.height,
        ratio = $width / $height;    //图片的真实宽高比例
    let screenWidth = app.globalData.screenWidth          //设置图片显示宽度，左右留有16rpx边距
    let viewHeight = ''
    let viewWidth = ''
    if ($width > screenWidth) {
      viewHeight = screenWidth / ratio;    //计算的高度值
    }
    else {
      viewHeight = $height
      viewWidth = $width
    }
    inst.update({'@image.itemStyle': `height: ${viewHeight}px; width: ${$width > screenWidth ? '100%' : viewWidth+'px'};`})
  },
  onFixedBtn(e, p, inst) {
    const _type = p.type
    inst.addClass('active')
  },
  bindchange(e) {
    let _current = e.detail.current
    const $swiperDot = this.getElementsById('swiper-dot-cu')
    const _newDot = $swiperDot.getData().data
    _newDot.map((item, ii) => {
      item.itemClass = ''
      if (ii === _current) {
        item.itemClass +=' active'
      }
      return item
    })
    $swiperDot.update(_newDot)
  },
  onShow: function () {},
  onReady: function () {
    const that = this
    this.vm = this
    this.$detail = this.getElementsById('detail')
    this.$detail.update(this.data, () => {      
      that.$menus = that.getElementsById('menus')
      that.$menus.update({
        data: that.contentData.menus
      }, () => {
        that.getMenusQuery()
        that.getScrollQuery()
        that.ass('.himg')
      })
    })
  },
  getMenusQuery() {
    const xx = wx.createSelectorQuery().in(this)
    const that = this
    setTimeout(() => {
      xx.selectAll('.boxer>>>.item-menus').boundingClientRect().exec(ret=>{
        if (ret[0] === null) return;
        that.itemMonitorMenus = ret[0]
      })
    }, 10);
  },
  ass(idStr) {
    const that = this
    const scrollQuery = wx.createSelectorQuery(this)
    setTimeout(() => {
      scrollQuery.selectAll(idStr).boundingClientRect()
      scrollQuery.exec((res) => {
        let isOk = true; //图片渲染完成标志
        console.log('======res[], ', res[0]);
        
        //检验是否渲染完成
        res[0].some(item => {
          if (item.height == 0) {
            isOk = false;
            return true;
          }
        })
        //没通过检验
        if (!isOk) {
          setTimeout(() => {
            _this.ass(idStr);
          }, 10);
          return;
        } else {
          //通过检验
          console.log('==========', res);
          
        }
      })
    }, 10);
  },
  getScrollQuery(id, cb) {
    const that = this
    const scrollQuery = wx.createSelectorQuery(this)
    setTimeout(() => {
      scrollQuery.select('.boxer>>>#c_ss_1').boundingClientRect()
      scrollQuery.select('.boxer>>>#c_ss_2').boundingClientRect()
      scrollQuery.select('.boxer>>>#c_ss_3').boundingClientRect()
      scrollQuery.select('.boxer>>>#c_ss_4').boundingClientRect()
      scrollQuery.select('.boxer>>>#c_ss_5').boundingClientRect()
      scrollQuery.exec((res) => {
        that.execData = res
      })
    }, 10);
  },
  scrollUpdateMenus(idx) {
    this.getMenusQuery()
    const _ndata = this.$menus.getData().data
    let _id = ''
    _ndata.map((item, ii) => {
      item.itemClass = ''
      if (ii == idx || item.id === idx) {
        idx = ii
        item.itemClass +=' active'
      }
      return item
    })
    if (this.itemMonitorMenus && ((this.itemMonitorMenus[idx].left + this.itemMonitorMenus[idx].width) >= app.globalData.screenWidth || this.itemMonitorMenus[idx].left < 0)) {
      _id = this.itemMonitorMenus[idx].id
    }
    let scrollCfg = {}
    if (idx !== 0) {
      scrollCfg = {'type.scroll-into-view': _id}
    }
    else {
      scrollCfg = {'type.scroll-left': 0}
    }
    this.$menus.update({data: _ndata, ...scrollCfg})
  },
  kkk: false,
  hasIdx: 0,      //为了不重复执行
  preScrollTop: null,
  clickMenused: false,
  bindscroll: debounce(function(res) {
    let scrolltop = res[0].detail.scrollTop
    if (!this.clickMenused && this.execData[0].top) {
      if (scrolltop >= this.execData[0].top) {
        this.$menus.css('--show: flex')
        // const xx = this.execData.find((item, index) => scrolltop >= this.execData[index - 1] && scrolltop <= this.execData[index])
        // const xx = this.execData.find(item => scrolltop >= item.top && scrolltop < parseFloat(item.top + item.height))
        // console.log('xxxx', xx);
        
        this.execData.forEach((item, ii) => {
          if (ii  > 0) {
            console.log('=======', scrolltop >= this.execData[ii - 1].top, scrolltop <= this.execData[ii].top)
            if (scrolltop >= this.execData[ii - 1].top && scrolltop <= this.execData[ii].top) {
              console.log('id, ', item.id);
              if (this.hasIdx != ii) {
                // console.log('=======222', ii);
                this.scrollUpdateMenus(ii)
                this.hasIdx = ii
              }
            }
          }
        })
      }
      else {
        this.$menus.css('--show: none')
      }
    }
    else {
      this.clickMenused = false
      return false
    }
    
  }),
  onLoad: function (options) {
    if (options.from) {
      this.data = this.adapter(_normal)
    }
    else {
      this.data = this.adapter(data.data, true)
    }
  },
  // onUnload: function () { 
  //   clearTimeout()
  // },
})
